package com.apes.scm.stock.transfer.model;

import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.model.StockUsage;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 功能： 转储订单（公司内）
 *
 * @author wuq
 * @create 2018-06-21 17:10
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = Transfer.CONST_TABLE_NAME)
public class Transfer extends Model {
    public static final String CONST_TABLE_NAME = "stock_transfer";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "转储订单", prefix = "ZC%(company)%(yy)%(month)", padding = 4, useDateRange=true)
    @Comment("转储订单编码")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "origin_location_id", referencedColumnName = "id", nullable = false)
    @Comment("发货仓库编码")
    private Location originLocation; //发货仓库

    @Comment("公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    private PartyRole company;

    @Column(name = "source", length = 30)
    @Comment("来源单号")
    private String source;

    @Column(name = "source_business_type", length = 32)
    @Comment("来源单据类型")
    private String sourceBusinessType;

    @Column(name = "source_business_type_name", length = 64)
    @Comment("来源单据类型名称")
    private String sourceBusinessTypeName;

    @Column(name = "special_documents", length = 30)
    @Comment("特殊单据")
    private String specialDocuments; // 不用于追朔原单据

    @Column(name = "special_documents_type", length = 30)
    @Comment("特殊单据类型")
    private String specialDocumentsType;

    @Transient
    private StockUsage usage; //库区类型

    public StockUsage getUsage() {
        if( originLocation == null ) return null;
        return originLocation.getUsage();
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "receipt_location_id", referencedColumnName = "id", nullable = false)
    @Comment("收货仓库编码")
    private Location receiptLocation; //收货仓库

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "Transfer_type", referencedColumnName = "id")
    @Comment("转储类型")
    private Enumeration transferType; //转储类型：(0:下发;1:平调;2:回调)

    @Column(name = "note", length = 120)
    @Comment("备注")
    private String note; //备注

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "reason", referencedColumnName = "id" )
    @Comment("转储原因")
    private Enumeration reason; //转储原因

    @States(name = "订单状态", values = {
            @State(id = "sent", name = "创建"),
            @State(id = "delete", name = "删除"),
            @State(id = "approve", name = "审核"),
            @State(id = "delivery", name = "交货中"),
            @State(id = "done", name = "交货完成") })
    @Column(name = "state", length = 10, nullable = false)
    private String state; //状态

    @Column(name = "create_date")
    @Comment("制单日期")
    private Date createDate; //制单日期

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审批人")
    private PartyRole approveUid; //审批人

    @Column(name = "date_approve")
    @Comment("审批日期")
    private Date approveDate; //审批日期

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "stop_uid", referencedColumnName = "id")
    @Comment("终止人")
    private PartyRole stopUid; //终止人

    @Column(name = "stop_date")
    @Comment("终止日期")
    private Date stopDate; //终止日期

    @OneToMany(mappedBy = "transfer", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<TransferItem> transferItems = new HashSet(); //订单行
    public Set<TransferItem> getTransferItems() {
        for (TransferItem item : transferItems) {
            item.setTransfer(this);
        }
        return transferItems;
    }

    @Column(name = "transfer_direction")
    @Comment("跨公司转储方向(0:正向,1:逆向)")
    private String transferDirection;   //  正向：forward, 反向： reverse


    @Column(name = "origin", length = 30)
    @Comment("原始单据")
    private String origin;

    @Column(name = "origin_business_type", length = 32)
    @Comment("原始单据类型")
    private String originBusinessType;

    @Column(name = "print_number", columnDefinition = "number(4,0) default 0")
    @Comment("打印次数")
    private double printNumber;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "create_uid", referencedColumnName = "id")
    @Comment("创建人")
    private PartyRole createUid;

    /**
     * 检查是否跨公司
     */
    @Comment("是否跨公司")
    @States(name = "是否跨公司", values = {
            @State(id = "true", name = "是"),
            @State(id = "false", name = "否")})
    @Column(name = "cross", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    private boolean cross = false;

    public boolean checkCross() {
        this.cross = !getOriginLocation().getCompany().getId().equals( getReceiptLocation().getCompany().getId() );
        return cross;
    }


    @Comment("明细数量是否全部完成")
    @Column(name = "item_qty_complete", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    private boolean itemQtyComplete = false;

    @Column(name = "customer_Expand_Id")
    @Comment("会员扩展表")
    private String customerExpandId;

    @Transient
    private Map formatCustomerExpandId;

    public Map getFormatCustomerExpandId() {
        if (StringUtils.isEmpty(customerExpandId)) return formatCustomerExpandId = null;
        String carLicense = SpringManager.getBean(DomainService.class).invoke("fn.fnCustomerExpandService.accordIdFindCarLicense", MapUtil.mapper("id", customerExpandId));
        return formatCustomerExpandId = MapUtil.mapper("id", customerExpandId, "carLicense", carLicense);
    }


    /***
     * 自动转储(通过逻辑仓判断)
     */
    public boolean checkAuto(){
        return getOriginLocation().getDepot().getId().equals(getReceiptLocation().getDepot().getId());
    }

    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if(this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }


    @Transient
    private double withDrawDiveryQtySum = 0;

    public double getWithDrawDiveryQtySum() {
        return this.withDrawDiveryQtySum;
    }

    @Transient
    private boolean hideTerminationButton = true;

    public boolean getHideTerminationButton() {
        TransferItem transferItem = this.getTransferItems().stream().filter(item -> item.getTransferQty() - item.getSendQty() - item.getFinishSum() > 0 && (this.getState().equals("approve") || this.getState().equals("delivery"))).findFirst().orElse(null);
        if (transferItem != null) return false;
        return this.hideTerminationButton;
    }

    @Transient
    private String batchRequireId; // 要货批量转储要货单号集合

    public double getPrintNumber() {
        return SpringManager.getBean(DomainService.class).invoke("print.record.findOne", MapUtil.mapper("id", this.getId()));
    }
}
